<!-- 集装箱公司/货代公司  购买->订单管理  公用此页面-->
<template>
  <div class="app-container">
     <div class="top-main">
    <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">  
      <el-form-item label="订单号">
        <el-input v-model.trim="param.orderNo" clearable  placeholder="请输入订单号"> </el-input>
      </el-form-item>
      <el-form-item label="购箱城市">
        <city-select :selectCity="param.boxStartCity" @cityId="startCityId"
          style="width: 100%;"></city-select>
      </el-form-item>
      <el-form-item label="预计提箱日期">
        <el-date-picker v-model="param.planPickupDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="下单日期">
        <el-date-picker v-model="param.createDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="箱贸企业">
        <el-input v-model.trim="param.companyName" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item label="结算币种">
        <el-select v-model="param.payCurrency" placeholder="请选择">
          <el-option v-for="item in param.payCurrencys" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="发票号">
        <el-input v-model.trim="param.invoiceNo" clearable  placeholder="请输入"> </el-input>
      </el-form-item>
    </el-form>
    <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReSet">重置</el-button>
      </div>   
    </div>
    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
    <span style="margin-top: -40px;float: right;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有订单" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button size="small" @click="exportExcel" plain>导出</el-button>
      <!-- <el-button :disabled="!param.status || param.status <= 15 || param.status == 40" :icon="Upload" type="primary"
        size="small" @click="handleApplyRefund" plain>申请退款</el-button>
      <el-button :disabled="param.status != 10" :icon="Download" type="primary" size="small" @click="handleApplyInvoice"
        plain>申请发票</el-button> -->
      <el-button type="primary" size="small" @click="batchDelete" plain>删除</el-button>
    </span>
    <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" @pageChange="onTablePageChange" @showInfo="showInfo" @deleteItem="deleteItem" @handlePay="handlePay"
      @handleShowContract="handleShowContract" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!-- 退款 -->
    <el-dialog v-model="param.dialogVisible" width="60%">
      <refundCard :selection="tableRef.multipleSelection" :opr="'apply'" @close="handleClose"></refundCard>
    </el-dialog>
    <!-- 发票 -->
    <el-dialog v-model="param.dialogVisibleInvoice">
      <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>发票信息
      </div>
      <div style="height:180px;overflow: auto;margin-bottom: 10px">
        <invoice-template></invoice-template>
      </div>
      <el-form inline label-position="left" style="color: black;margin-bottom: 10px">
        <el-form-item label="发票状态:"><span style="color: green;">{{ '待开票' }}</span></el-form-item>
        <el-form-item label="发票内容:">{{ '明细' }}</el-form-item>
        <el-form-item label="发票抬头:">{{ '企业' }}</el-form-item>
        <el-form-item label="联系箱贸企业商:">{{ }}</el-form-item>
        <el-form-item label="在线咨询">
          <el-button type="primary" size="large" style="font-size: 15px;" link icon="ChatDotRound"></el-button>
        </el-form-item>
      </el-form>
      <div style="border:none;border-top: 1px solid #a6a9ad;padding: 10px 0 10px 0;">
        <div style="font-weight: 700;font-size: 15px;margin-top: 20px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>申请发票
        </div>
        <el-form label-width="140px" label-position="left">
          <el-form-item>
            <redStar />
            <div style="width:120px">发票类型</div>
            {{ '增值税普通发票' }}
          </el-form-item>
          <el-form-item>
            <redStar />
            <div style="width:120px">企业名称</div>
            <el-input v-model="param.invoiceTitle" style="width: 400px;" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item>
            <redStar />
            <div style="width:120px">统一社会信用代码</div>
            <el-input v-model="param.creditCode" style="width: 400px;" placeholder="请输入统一社会信用代码"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <div style="font-weight: 700;font-size: 15px;margin-top: 20px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>支付购箱费
        </div>
        <el-table :data="param.orderTable" style="width: 100%">
          <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
          <el-table-column prop="carryCityName" label="购箱城市" width="180"></el-table-column>
          <el-table-column prop="createTime" label="下单日期" width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime, 2) }}
            </template>
          </el-table-column>
          <el-table-column prop="boxQuantity" label="订单箱量" width="180"></el-table-column>
          <el-table-column prop="amount" label="应付购箱费(￥)"></el-table-column>
        </el-table>
        <el-form inline style="margin-top: 20px">
          <el-form-item>
            <div style="width:80px">应付箱量：</div>
            {{ param.needPayNumber }} 个
          </el-form-item>
          <el-form-item>
            <div style="width:120px">应付购箱费总计：</div>
            ￥{{ param.needPay }}
          </el-form-item>
          <el-form-item>
            <redStar />
            <div style="width:120px">实付购箱费总计：</div>
            ￥&nbsp; <el-input v-model="param.actPay" style="width:150px"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-top: 20px;width: 100%;text-align: center;">
        <el-button type="primary" style="width: 100px;" @click="applyInvoice">提交</el-button>
      </div>
    </el-dialog>


    <!-- 支付 -->
    <el-dialog v-model="param.dialogVisiblePay">
      <el-form label-width="200" style="margin: 50px 0 50px 100px;">
        <el-form-item label="优惠券">{{ 0 }}</el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="param.paymentMethod" style="width:220px" placeholder="选择">
            <el-option label="对公转账" value="5" />
            <el-option label="在线支付" value="10" />
          </el-select>
        </el-form-item>
        <el-form-item label="电子回执单">
          <input type="file" />
        </el-form-item>
        <el-form-item label="支付日期">
          <el-date-picker v-model="param.payDate" :editable="false" :clearable="false" type="date" placeholder="选择日期" />
        </el-form-item>
      </el-form>
      <div style="margin-top: 20px;width: 100%;text-align: center;">
        <el-button type="primary" style="width: 100px;" @click="activPay">确定</el-button>
      </div>
    </el-dialog>

    <!-- 订单申请协议 -->
    <el-dialog v-model="param.dialogContract" :with-header="false">
      <pdfViewer :url="param.contractUrl"></pdfViewer>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pdfViewer from '@/components/pdf'
import { formatDate } from '@/utils'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'
import invoiceTemplate from '@/views/components/invoiceTemplate'
import { payBoxLabelInvoice, addPurchaseBoxRequestInvoice, getInvoicesInfo } from '@/api/invoice'
import { getBuyPurchaseBoxOrderPage, exportAgentPurchaseBoxOrder,deleteOrderByIds, boxEastStatusCount,agentStatusCount} from '@/api/boxDeal/boxBuy'
import refundCard from '@/views/components/order/refundCard'
import { numMulti, numAdd } from '@/utils/compute'
import redStar from '@/views/components/redStar.vue';
import { computed, onMounted, onActivated, reactive, ref } from 'vue';
import { Finished, Download, Document, Upload } from '@element-plus/icons-vue'
import { useRouter,useRoute } from 'vue-router';
import { ElMessageBox,ElMessage } from 'element-plus'
import { downloadFile } from '@/utils/download'

const router = useRouter();
const param = reactive({
  payCurrencys: [{ label: '美元', value: 'USD' }, { label: '人民币', value: 'CNY' }], //美元:USD 人民币:CNY
  paymentMethod: '5',
  payDate: new Date(),
  orderTable: [],

  loading: false,
  pageNum: 1,
  pageSize: 10,
  stateFilter: { 2: '待确认', 3: '待审核', 10: '待开发票', 15: '未付', 20: '已付', 25: '待提', 30: '已提', 35: '已完成', 40: '已取消', 45: '待取消' },
  // stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  status:''
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'orderNo', key2: 'refundStatusName', colWidth: '200', title: '订单号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'carryCityName', key2: 'carryCountryName', colWidth: '80', title: '购箱城市', type: 'twoRow', isCheck: true },
    { key: 'createTime', colWidth: '140', title: '下单日期', type: 'dateTime', isCheck: true },
    { key: 'planPickupDate', colWidth: '120', title: '预计提箱日期', type: 'date', isCheck: true },
    { key: 'boxType', colWidth: '80', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '80', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' }, isCheck: true },
    { key: 'boxQuantity', colWidth: '70', title: '箱量', type: 'text', isCheck: true },
    { key: 'actualPayAmount', colWidth: '120', title: '订单金额', type: 'add', currency: 'currency', isCheck: true },
    { key: 'status', colWidth: '80', title: '订单状态', type: 'filter', filter: param.stateFilter, isCheck: true },
    { key: 'boxEastUserName', colWidth: '120', title: '联系人', type: 'text', isCheck: true },
    { key: 'boxEastUserTel',key2: 'boxEastUserAreaCode', colWidth: '150', title: '联系电话', type: 'mobileCode',isCheck: true },
    { key: 'invoiceNo', colWidth: '180', title: '发票号', type: '<a>', command: '', isCheck: true },
    {
      key: 'operate',
      colWidth: '120',
      title: '订单申请协议',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: Document,
          command: 'handleShowContract',
          isShow: (row) => {
            return row.downloadUrl
          },
        },
      ]
    },
    { key: 'companyName', colWidth: '200', title: '集装箱公司', type: 'text', isCheck: true },
    {
      key: 'operate',
      colWidth: '80',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        // {
        //   content: '支付',
        //   icon: 'Money',
        //   command: 'handlePay',
        //   isShow: (row: { status: string; }) => {
        //     return row.status == '15';
        //   },
        // },
        {
          // content: '支付',
          // icon: 'Money',
          command: 'deleteItem',
          name:'删除',
          isShow: (row) => {
            return row.status == 35   // refundStatus 5-待确认 10-已确认 15-待退款 20-已退款。
          },
        },

      ]
    }
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

// const typeList = computed(() => {
//   const list = [
//     { id: 0, name: '全部' },
//     { id: 2, name: '待确认' },
//     { id: 3, name: '待审核' },
//     { id: 10, name: '待开发票' },
//     { id: 15, name: '未付' },
//     { id: 20, name: '已付' },
//     { id: 25, name: '待提' },
//     { id: 30, name: '已提' },
//     { id: 35, name: '已完成' },
//     { id: 45, name: '待取消' },
//     { id: 40, name: '已取消' },
//   ]
//   return list
// })
const typeList = ref([
    { id: 0, name: '全部',num:0 },
    { id: 2, name: '待确认',num:0 },
    { id: 3, name: '待签署' ,num:0 },
    // { id: 10, name: '待开发票',num:0  },
    // { id: 15, name: '未付' ,num:0 },
    // { id: 20, name: '已付' ,num:0 },
    { id: 25, name: '待提' ,num:0 },
    { id: 30, name: '已提' ,num:0 },
    { id: 35, name: '已完成' ,num:0 },
    { id: 45, name: '待取消',num:0  },
    { id: 40, name: '已取消' ,num:0 },
])
function handleTypeChange(val: any) {
  param.status = val
  getTableData()
  deselectAll()
}

// 获取表格数据
function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    orderNo: param.orderNo?.toUpperCase(),
    carryCityId: param.boxStartCity,
    companyName: param.companyName,
    // buyBoxCompanyId: param.buyBoxCompanyId,
    currency: param.payCurrency,
    invoiceNo: param.invoiceNo?.toUpperCase(),
    status: param.status || null
  }
  if (param.createDate) {
    data.beginCreateDate = param.createDate[0]
    data.endCreateDate = param.createDate[1]
  }
  if (param.planPickupDate) {
    data.beginPlanPickupDate = param.planPickupDate[0]
    data.endPlanPickupDate = param.planPickupDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getBuyPurchaseBoxOrderPage(data).then(res => {
    const statusFilter = { 5: '确认退款中', 10: '已确认退款', 15: '待退款', 20: '已退款', } //5 - 待确认 10 - 已确认 15 - 待退款 20 - 已退款
    table.data = res.data.list;
    table.data.forEach(item => {
      if (!item.refundStatus) return
      item.refundStatusName = statusFilter[item.refundStatus]
    })
    table.config.total = res.data.total;
    getboxEastStatusCount()
  });
  table.config.loading = false;
}

// 查询各状态数量
async function getboxEastStatusCount(){
  let reqParam = {
    orderNo: param.orderNo,
    carryCityId: param.boxStartCity,
    beginPlanPickupDate:'',
    endPlanPickupDate:'',
    beginCreateDate:'',
    endCreateDate:'',
    companyName: param.companyName,
    currency: param.payCurrency,
    invoiceNo: param.invoiceNo?.toUpperCase(),

  }
  if (param.createDate) {
    reqParam.beginCreateDate = param.createDate[0]
    reqParam.endCreateDate = param.createDate[1]
  }
  if (param.planPickupDate) {
    reqParam.beginPlanPickupDate = param.planPickupDate[0]
    reqParam.endPlanPickupDate = param.planPickupDate[1]
  }
  const routerPath =  router.currentRoute.value.path;
  // if(routerPath.includes('hdzxgm')){
    await agentStatusCount(reqParam).then(res => { 
      if(res.code == '00000'){
        typeList.value.forEach(item => { 
          item.num = 0
          res.data.forEach(item1 => { 
            if(item.id == 0){ //全部
              item.num += item1.totalQty
            }else if(item.id == 2 && item1.status ==2){ //待确认
                item.num += item1.totalQty
            }else if(item.id == 3 && item1.status == 3){ //待审核
                item.num += item1.totalQty
            }else if(item.id == 5 && item1.status == 5){ //待开提箱单
                item.num += item1.totalQty
            }else if(item.id == 10 && item1.status == 10 ){ //待提
                item.num += item1.totalQty
            }else if(item.id == 15 && item1.status == 15){ //已提
                item.num += item1.totalQty
            }else if(item.id == 20 && item1.status == 20){ //待还
                item.num += item1.totalQty
            }else if(item.id == 25 && item1.status == 25){ //已还
                item.num += item1.totalQty
            }else if(item.id == 30 && item1.status == 30){ //已完成
                item.num += item1.totalQty
            }else if(item.id == 40 && item1.status == 40){ //待取消
                item.num += item1.totalQty
            }else if(item.id == 35 && item1.status == 35){ //已取消
                item.num += item1.totalQty
            }else if(item.id == 45 && item1.status == 45){ //已取消
                item.num += item1.totalQty
            }
        
          });
        });
      
      }
    })

  // }else if(routerPath.includes('xdzxgm')){ 
  //   await boxEastStatusCount(reqParam).then(res => { 
  //     if(res.code == '00000'){
  //       typeList.value.forEach(item => { 
  //         item.num = 0
  //         res.data.forEach(item1 => { 
  //           if(item.id == 0){ //全部
  //             item.num += item1.totalQty
  //           }else if(item.id == 2 && item1.status ==2){ //待确认
  //               item.num += item1.totalQty
  //           }else if(item.id == 3 && item1.status == 3){ //待审核
  //               item.num += item1.totalQty
  //           }else if(item.id == 5 && item1.status == 5){ //待开提箱单
  //               item.num += item1.totalQty
  //           }else if(item.id == 10 && item1.status == 10 ){ //待提
  //               item.num += item1.totalQty
  //           }else if(item.id == 15 && item1.status == 15){ //已提
  //               item.num += item1.totalQty
  //           }else if(item.id == 20 && item1.status == 20){ //待还
  //               item.num += item1.totalQty
  //           }else if(item.id == 25 && item1.status == 25){ //已还
  //               item.num += item1.totalQty
  //           }else if(item.id == 30 && item1.status == 30){ //已完成
  //               item.num += item1.totalQty
  //           }else if(item.id == 40 && item1.status == 40){ //待取消
  //               item.num += item1.totalQty
  //           }else if(item.id == 35 && item1.status == 35){ //已取消
  //               item.num += item1.totalQty
  //           }else if(item.id == 45 && item1.status == 45){ //已取消
  //               item.num += item1.totalQty
  //           }
        
  //         });
  //       });
      
  //     }
  //   })
  // }
}

// 重置
const handleReSet = () => {
  param.orderNo = null
  param.createDate = null
  param.planPickupDate = null
  param.payCurrency = null
  param.invoiceNo = null
  param.companyName = null
  param.boxStartCity = null
  param.carryCityId = null
  getTableData()
}

//查看协议
const handleShowContract = (row: any) => {
  param.dialogContract = true
  const downloadUrl = JSON.parse(row.downloadUrl)
  param.contractUrl = downloadUrl.url
}

//分页
function onTablePageChange(page) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//申请发票
const tableRef = ref({ multipleSelection: [] })
const handleApplyInvoice = (row: any) => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  if (checkAllItem.length == 0) {
    ElMessage.warning('请选择要 申请发票 的订单')
    return
  }
  param.dialogVisibleInvoice = true
  param.orderTable = []
  param.needPayNumber = 0
  param.needPay = 0
  checkAllItem.forEach(item => {
    let itemInfo = {
      orderNo: item.orderNo,
      carryCityName: item.carryCityName,
      createTime: item.createTime,
      boxQuantity: item.boxQuantity,
      amount: item.amount,
    }
    param.orderTable.push(itemInfo)
    param.needPayNumber = numAdd(item.boxQuantity, param.needPayNumber)
    param.needPay = numAdd(item.amount, param.needPay)
  })
}
const applyInvoice = () => {
  if (!param.invoiceTitle) {
    return ElMessage({ message: '请完善企业名称', type: 'warning' })
  }
  if (!param.creditCode) {
    return ElMessage({ message: '请完善统一社会信用代码', type: 'warning' })
  }
  if (!param.actPay) {
    return ElMessage({ message: '请完善实付购箱费', type: 'warning' })
  }
  const invoiceOrder = tableRef.value.multipleSelection.map(item => {
    return {
      "orderNo": item.orderNo,
      "orderId": item.id
    }
  })
  const data = {
    "invoiceOrder": JSON.stringify(invoiceOrder),
    "invoiceTitle": param.invoiceTitle,
    "invoiceContent": "申请发票",
    "creditCode": param.creditCode,
    "tel": rowData.value.tel || ''
  }
  addPurchaseBoxRequestInvoice(data).then((res: any) => {
    getTableData()
    param.dialogVisibleInvoice = false
  })
}

//支付
const rowData = ref({})
const handlePay = (row: any,) => {
  param.dialogVisiblePay = true
  rowData.value = row
}
// 删除
const deleteItem =(row: any) => { 
  ElMessageBox.confirm('确定要删除订单么？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOrderByIds([row.id]).then((res: any) => { 
      if(res.code != '00000'){
        ElMessage.warning(res.msg)
      }else{
        getTableData()
        ElMessage.success('删除成功！')
      }
    })
  }).catch(() => { });
}
//批量删除
const batchDelete = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
  ElMessageBox.confirm('确定要删除订单么？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOrderByIds(ids).then((res: any) => { 
      if(res.code != '00000'){
        ElMessage.warning(res.msg)
      }else{
        getTableData()
        ElMessage.success('删除成功！')
      }
    })
  })
}

const activPay = () => {
  if (!rowData.value.amount) {
    return ElMessage({ message: '购箱费不能为空', type: 'warning' })
  }
  if (param.payDate > new Date()) {
    return ElMessage({ message: '支付时间不能大于当前时间', type: 'warning' })
  }
  const data = {
    "id": rowData.value.invoiceId, //发票id
    "paymentMethod": param.paymentMethod,
    "payDate": param.payDate,
    "payUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"returnReceiptFileName\":\"国际贸易供应链数字平台电子回执单.docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]",
    "couponAmount": 0, // 优惠
    "actualPayAmount": rowData.value.amount || 0,
  }
  payBoxLabelInvoice(data).then(res => {
    param.dialogVisiblePay = false
  })
}

//申请退款
const handleApplyRefund = (row: any) => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  if (checkAllItem.length == 0) {
    ElMessage.warning('请选择要 申请退款 的订单')
    return
  }
  param.dialogVisible = true
}
const handleClose = () => {
  param.dialogVisible = false
  getTableData()
}



//
const showInfo = (row: any) => {
  // router.push('agentBuyOrderInfo')
  orderInfo().setRowData(row)
  router.push({
    path: 'tradeOrder/details',
    query: {
      orderId: row.id,
      sourceType: 'view',
      businessRoleEnum: 5  // 5:买箱 10：卖箱
    }
  })
}


// 城市id回写
const startCityId = (id: string) => {
  param.boxStartCity = id
}
const backCityId = (id: string) => {
  param.boxBackCity = id
}

const route = useRoute();

onActivated(() => {
  if(route.query.refNo){
    param.orderNo=route.query.refNo
  }
  getTableData()
})

const exportExcel = () => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
    const ids = checkAllItem.map((item: any) => item.id)
    if (ids.length < 1) return ElMessage.warning('请选择要导出的购箱订单！')
    ElMessageBox.confirm('确认要导出选中的购箱订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let reqParameters = {
          purchaseIds: ids
        }
        exportAgentPurchaseBoxOrder(reqParameters).then((res: any) => {
            downloadFile(res, '购箱订单详情')
          
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
}


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    let data = {
      pageNum:1,
      pageSize:10000,
      status: param.status || ''
    }
    await getBuyPurchaseBoxOrderPage(data).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}
</script>